package com.pri.chat.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.WishListBean;
import com.netease.nim.uikit.net.entity.WishMoney;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.adapter.OtherWishAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.OtherModel;
import com.pri.chat.model.UserModel;
import com.pri.chat.model.WishModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideEngine;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author
 * @time 2020/5/9
 */
public class OtherWishActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    @BindView(R.id.ywjjRelation)
    View ywjjRelation;
    @BindView(R.id.wishMoney)
    TextView wishMoney;
    @BindView(R.id.jiaSuBtn)
    TextView jiaSuBtn;

    @BindView(R.id.dakaImageView)
    ImageView dakaImageView;



    private int canJiaSu = 0;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_wish_layout;
    }

    private String mOtherId;

    private MyReceiver myReceiver;
    @Override
    protected void initView() {
        mOtherId = getIntent().getExtras().getString("id");
        String mOtherName = getIntent().getExtras().getString("name");
        canJiaSu = getIntent().getExtras().getInt("canJiaSu");
        setTitle("愿望");
        iv_paizhao.setVisibility(View.VISIBLE);
        wishMoney.setText("");
        srlAll.setEnableLoadmore(false);
        initLayout();
        initSrl();
        getWishMoney();

        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.UPDATE_WISH);
        filter.addAction(MainActivity.DELETE_WISH);

        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, filter);

        if(canJiaSu == 1){
            jiaSuBtn.setBackgroundResource(R.drawable.btn_gray_20_shape);
        }

        jiaSuBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(canJiaSu == 0){
                    httpCallFriends();
                }
            }
        });

        iv_paizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxActivityTool.skipActivity(mContext, ReleaseWishAcctivity.class);
            }
        });
    }

    private void getWishMoney() {
        SubscriberOnNextListener<BaseBean<String>> onNextListener = baseBean -> {
            wishMoney.setText(baseBean.getData());
        };
        Map<String,Object> params = new HashMap<>();//登录上传参数
        params.put("memberId",mOtherId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getWishMoney(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(myReceiver);
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(MainActivity.UPDATE_WISH.equals(intent.getAction())){
                WishListBean wishObj = intent.getExtras().getParcelable("wishObj");
                for(int i=0;i<mList.size();i++){
                    if(mList.get(i).getId().equals(wishObj.getId())){
                        mAdapter.setData(i,wishObj);
                        break;
                    }
                }
            }else if(MainActivity.DELETE_WISH.equals(intent.getAction())){
                WishListBean wishObj = intent.getExtras().getParcelable("wishObj");
                for(int i=0;i<mList.size();i++){
                    if(mList.get(i).getId().equals(wishObj.getId())){
                        mAdapter.remove(i);
                        break;
                    }
                }
            }
        }
    }

    private List<WishListBean> mList;
    private OtherWishAdapter mAdapter;
    private int page = 1;
    private boolean isShowDialog = false;

    private void initLayout() {

        if(mOtherId.equals(SharedHelper.readId(mContext))){
            ywjjRelation.setVisibility(View.GONE);
        }else{
            dakaImageView.setVisibility(View.GONE);
        }
        mList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter = new OtherWishAdapter(R.layout.item_wish, mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnImageClickListener((view, c_pos, f_pos) -> {
            PictureSelector.create(this)
                    .themeStyle(R.style.picture_default_style)
                    .isNotPreviewDownload(true)
                    .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                    .openExternalPreview(c_pos, mList.get(f_pos).getMediaList());
        });

        dakaImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtil.getInstance().shareWechatMoments("http://nbninikeji.com/202010271048341603766914940.png","萤火——为我的梦想打卡，加油！","萤火——为我的梦想打卡，加油！",HttpMethods.SHARE_URL);
            }
        });

    }

    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<WishListBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                RxToast.normal(getString(R.string.no_data));
            } else {
                none.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                for (int i = 0; i < mList.size(); i++) {
                    String[] imgs = mList.get(i).getPicList().split(",");
                    List<String> list = new ArrayList<>();
                    List<LocalMedia> mediaList = new ArrayList<>();
                    for (int j = 0; j < imgs.length; j++) {
                        LocalMedia localMedia = new LocalMedia();
                        list.add(imgs[j]);
                        localMedia.setPath(imgs[j]);
                        mediaList.add(localMedia);

                    }
                    mList.get(i).setImgs(list);
                    mList.get(i).setMediaList(mediaList);
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        WishModel dtModel = new WishModel(0);
        dtModel.setMemberId(mOtherId);
        dtModel.setOtherMemberId(SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().listWish(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }

    private void httpGoWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("已通知对方");
            srlAll.autoRefresh();
        };
        WishModel dtModel = new WishModel(1);
        dtModel.setMemberId(SharedHelper.readId(this));
        dtModel.setWishId(mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().saveWishHelp(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(this, WishMsgActivity.class);
        Bundle bundle_2 = new Bundle();
        bundle_2.putParcelable("wish", mList.get(position));
        intent.putExtras(bundle_2);
        startActivityForResult(intent, 0x10);
    }

    private void refresh() {
        page = 1;
        isShowDialog = false;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        initData();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.tv_wish_go:
                TextView tv = (TextView)view;
                if(tv.getText().toString().equals("完成愿望")){
                    finishWish(position);
                }else{
                    if(mList.get(position).getCanHelp() == 0){
                        httpGoWish(position);
                    }
                }
                break;
            case R.id.iv_logo:
                Bundle bundle = new Bundle();
                bundle.putString("id", mList.get(position).getMemberId());
                RxActivityTool.skipActivity(OtherWishActivity.this, OtherPeopleMsgActivity.class, bundle);
                break;
            case R.id.iv_share:
                initShareDialog(mList.get(position).getPicList(),position);
                break;
        }
    }

    private void finishWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("操作成功");
            mList.get(pos).setStatus(1);
            mAdapter.notifyDataSetChanged();

            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            intent.setAction(MainActivity.UPDATE_WISH);
            bundle.putParcelable("wishObj", mList.get(pos));
            intent.putExtras(bundle);
            sendBroadcast(intent);
        };
        Map<String,Object> params = new HashMap<>();
        params.put("id",mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().finishWish(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    private Dialog mShareDialog;
    private void initShareDialog(String path,int pos) {
        String memberId = SharedHelper.readId(mContext);
        String listMemberId = mList.get(pos).getMemberId();
        int type = 1;
        if(listMemberId.equals(memberId)){
            type = 2;
        }
        mShareDialog= DialogUtil.getInstance().showShareDialog(activity,type);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("image",path);
                bundle.putString("title",mList.get(pos).getMemberName());
                bundle.putString("content",mList.get(pos).getContent());
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class,bundle);
                mShareDialog.dismiss();mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                //删除操作
                deleteWish(pos);
                mShareDialog.dismiss();
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }
            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("type","1");
                RxActivityTool.skipActivity(mContext, ReleaseJuBaoAcctivity.class,bundle);
            }
        });
        mShareDialog.show();
    }



    private void deleteWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("删除成功！");
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            intent.setAction(MainActivity.UPDATE_WISH);
            bundle.putParcelable("wishObj", mList.get(pos));
            intent.putExtras(bundle);
            sendBroadcast(intent);

            mAdapter.remove(pos);
        };
        Map<String,Object> params = new HashMap<>();
        params.put("id",mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteWish(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    private void httpCallFriends() {
        SubscriberOnNextListener<BaseBean<String>> onNextListener = baseBean -> {
            RxToast.normal("加速成功");
            canJiaSu = 1;
            jiaSuBtn.setBackgroundResource(R.drawable.btn_gray_20_shape);
            wishMoney.setText(baseBean.getData());
        };
        OtherModel otherModel = new OtherModel();
        otherModel.setMemberId(SharedHelper.readId(this));
        otherModel.setOtherMemberId(mOtherId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(otherModel));
        HttpMethods.getInstance().fridJiaSu(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
